// import store from '../store'
import config from '../config.js'
// import {isEmpty} from './validate.js'
let lastNetworkWatchTime = 0;
const http = {
	baseURL: config.network.baseUrl,
	config: {
	},
	reqInterceptor(config) {
		const localToken = uni.getStorageSync('token');
		if (localToken) {
			config.header = {
				Authorization: 'Bearer ' + localToken
			}
		}
		return config;
	},
	resInterceptor(res, options) {
		if (res.statusCode === 401) {
			uni.removeStorage({key: 'token'});
			uni.$emit('userLogin', {isLogin: false});
			uni.showToast({
				title: '请重新登录',
				icon: 'none'
			})
			setTimeout(() => {
				uni.switchTab({
					url: '/pages/index/index'
				})
				console.log('页面跳转');
			}, 2000);
		} else if (res.data) {
			const resCode = res.data.code;
			if (resCode === -1) {
				uni.showToast({
					title: res.data.msg,
					icon: 'none'
				});
			}
		} 
		return res;
	},
	request(options) {
		const _this = this;
		if (options.url.indexOf('http') === -1) {
			options.url = this.baseURL + options.url;
		}
		this.reqInterceptor(options);
		if (options.filter && options.data) {
			this.dataFilter(options.data);
		}
		return new Promise((resolve, reject) => {
			uni.request({
				..._this.config ,
				...options,
				success(res) {
					_this.resInterceptor(res, options);
					resolve(res);
				},
				fail(err) {
					console.log('请求失败', err);
					reject(err);
				},
				complete(data) {
					if (data && data.statusCode === 500) {
						uni.showToast({
							title: '服务器异常',
							icon: 'none'
						})
					}
				}
			});
		});
	},
	post(url, data, hint){
		return this.request({
			url,
			data,
			method: 'POST',
			hint
		});
	},
	get(url, data, hint, filter){
		return this.request({
			url,
			method: 'GET',
			data,
			hint,
			filter
		});
	},
	put(url, data, hint){
		return this.request({
			url,
			data,
			method: 'PUT',
			hint
		});
	},
	delete(url, data, hint){
		return this.request({
			url,
			data,
			method: 'DELETE',
			hint
		});
	},
	dataFilter(data) {
		if (data && (typeof data) === 'object' && !Array.isArray(data)) {
			const keys = Object.keys(data);
			Object.keys(data).forEach(key => {
				if (isEmpty(data[key])) {
					delete data[key]
				}
			})
		}
	}
};

function jumpToMain(title) {
	//store.commit('setCurrentPro', null);
	uni.showToast({
		icon: 'none',
		mask: true,
		title,
	});
	setTimeout(() => {
		uni.reLaunch({
		    url: '/pages/main/main'
		});
	}, 1500);
}
export default http